<template>
  <div class="cost-summary">
    <ProTable
      ref="merchant_settle_rule_table"
      immediate
      :request="queryMerchantSettleRuleList"
      :search-form="formList"
      :columns="columns"
      :pagination="true"
      :before-search-submit="beforeSearchSubmit"
    >
      <template #extra>
        <Authc permissions="trade:merchant:commercial:edit">
          <Button type="primary" @click="add">新增</Button>
        </Authc>
      </template>
    </ProTable>

    <Modal v-model="isAddShow" :visible.sync="isAddShow" title="添加商户清分规则" width='750' class="ruleModal">
      <Form ref="merchantSettleRuleModule" :label-width="130" :model="dataModule" inline :rules="ruleValidate">
        <FormItem label="所属商户" prop="merchantSelect" style="width:100%">
          <Select v-model="dataModule.merchantSelect" :label-in-value="true" filterable clearable placeholder="请选择"
                  @on-change="bindleMCode">
            <Option v-for="(item, index) in merchantList" :key="item + index" :value="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <Row>
          <Col span="11">
            <FormItem label="清分周期类型：" prop="cycleType">
              <Radio-group v-model="dataModule.cycleType">
                <Radio label="T" value="T">按日(T)</Radio>
                <Radio label="M" value="M">按月(M)</Radio>
              </Radio-group>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="清分日期：" v-if="dataModule.cycleType === 'T'">
              <span v-if="dataModule.cycleValue">T + <span
                style="font-weight: bold;color: red;font-size:20px;padding: 0 10px">{{ dataModule.cycleValue }}</span>日</span>
            </FormItem>
            <FormItem label="清分日期：" v-if="dataModule.cycleType === 'M'">
              <span>每月<span
                style="font-weight: bold;color: red;font-size:20px;padding: 0 10px">{{ dataModule.cycleValue }}</span>号 </span>
            </FormItem>
          </Col>
        </Row>
        <FormItem prop="cycleValue" label="清分周期值：" style="width:100%">
          <Input type="text" v-model="dataModule.cycleValue" placeholder="请填写清分周期值，1至28之间的的整数值"/>
        </FormItem>

        <FormItem label="清分规则：" prop="clearingRule">
          <Radio label="百分比" disabled :value="true">百分比 &#160;&#160;</Radio>
        </FormItem>
        <Row>
          <Col span="12">
            <FormItem style="width:100%" label="平台应收：" prop="platformPercent"
                      :rules="{ required: true, validator: validateTage, trigger: 'blur' }">
              <Input type="text" v-model="dataModule.platformPercent" placeholder="请填写"
                     @on-change="changePlatform" style="width:100%">
                <span slot="append">%</span>
              </Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem style="width:100%" label="商户应收：" prop="merchantReceivable"
                      :rules="{ required: true, validator: validateTage, trigger: 'blur' }">
              <Input type="text" v-model="dataModule.merchantReceivable" placeholder="请填写"
                     @on-change="changeMerchant" style="width:100%">
                <span slot="append">%</span>
              </Input>
            </FormItem>
          </Col>
        </Row>

        <FormItem label="备注：" style="width:100%">
          <Input v-model="dataModule.remark" maxlength="200" show-word-limit type="textarea" :rows="4"
                 placeholder="备注一下吧..."/>
        </FormItem>
      </Form>

      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel('merchantSettleRuleModule')">取消</Button>
        <Button type="primary" @click="handleSubmit('merchantSettleRuleModule')">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import ProTable from '@/components/ProTable';
import {omit} from 'lodash';
import {
  getMerchantAllMerchant,
  queryMerchantSettleRuleList,
  submitMerchantSettleRule,
  queryMerchantSettleRuleOne
} from '@/api/statement';
import {getDateYMD, getDateRangeDate} from '@/utils/date';
import Authc from "@/components/Authc";
import util from '@/utils/util';
import {namespace} from "../module/rule";
import {Modal} from "view-design";

export default {
  name: 'MerchantSettleRule',
  components: {
    ProTable,
    Authc
  },
  data() {
    return {
      isAddShow: false,
      dataModule: {},
      ruleValidate: {
        merchantSelect: [{required: true, message: "请选择", trigger: "change"}],
        cycleType: [{required: true, message: '请选择', trigger: 'change'}],
        cycleValue: [{required: true, validator: util.validateDay, trigger: "blur"}],
        expireDate: [{required: true, validator: util.validateNull, trigger: "change", message: '请选择失效日期'}],
      },
      merchantList: [],
      formList: [
        {
          type: 'select',
          name: 'merchantCode',
          label: '商户名称',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [],
            clearable: true,
            filterable: true
          }
        },
        {
          type: 'input',
          name: 'merchantCodeInput',
          label: '商户编码',
          value: '',
          props: {
            placeholder: '请输入商户编码',
            clearable: true,
          }
        },
        {
          type: 'input',
          name: 'ruleCode',
          label: '规则编码',
          value: '',
          props: {
            placeholder: '请输入规则编码',
            clearable: true,
          }
        },
        {
          type: 'select',
          name: 'ruleStatus',
          label: '规则状态',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [
              {
                value: 1,
                label: '生效'
              },
              {
                value: 2,
                label: '失效'
              }
            ],
            clearable: true,
            filterable: true
          }
        },
      ],
      columns: [
        {
          title: '规则编码',
          key: 'ruleCode',
          align: 'center',
        },
        {
          title: '商户名称',
          key: 'merchantName',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'a',
                {
                  on: {
                    click: () => this.gotoMerchantList(params.row)
                  }
                },
                params.row.merchantName
              )
            ]);
          }
        },
        {
          title: '商户编码',
          key: 'merchantCode',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'a',
                {
                  on: {
                    click: () => this.gotoMerchantList(params.row)
                  }
                },
                params.row.merchantCode
              )
            ]);
          }
        },
        {
          title: '清分周期类型',
          key: 'systemSource',
          align: 'center',
          width:'80',
          render: (h, params) => {
            let text = '按日'
            if (params.row.cycleType === 'M') {
              text = '按月'
            }
            return h('span', text)
          }
        },
        {
          title: '清分周期',
          key: 'systemSource',
          align: 'center',
          width:'80',
          render: (h, params) => {
            let text=''
            if (params.row.cycleType === 'M') {
              text = `${params.row.cycleType}&${params.row.cycleValue}`
            }else{
              text=`${params.row.cycleType}+${params.row.cycleValue}`
            }
            return h('span', text)
          }
        },
        {
          title: '规则状态',
          key: 'ruleStatus',
          align: 'center',
          width:'100',
          render: (h, params) => {
            if (params.row.ruleStatus === 1) {
              return h('Tag', {props: {color: 'success'}}, '生效')
            }
            if (params.row.ruleStatus === 2) {
              return h('Tag', {props: {color: 'error'}}, '作废')
            }
            return h('Tag', {props: {color: 'warning'}}, '未知')
          }
        },
        {
          title: '结算类型',
          key: 'settlementType',
          align: 'center',
          width:'80',
        },
        {
          title: '平台分佣',
          key: 'platformPercent',
          align: 'center',
          width:'80',
          render: (h, params) => {
            return h('span', `${params.row.platformPercent}%`)
          }
        },
        {
          title: '添加时间',
          key: 'createdDt',
          align: 'center',
          width:'170',
        },
        {
          title: '失效时间',
          key: 'expireDate',
          align: 'center',
          width:'170',
        },
        {
          title: '备注',
          key: 'remark',
          align: 'center',
        }
      ]
    };
  },
  beforeMount: async function() {
    let ruleCode = this.$route.query.ruleCode;
    if(ruleCode){
      this.formList.map(item => {
        if (item.name === 'ruleCode') {
          item.value= ruleCode
        }
      })
    }
    let merchantCode = this.$route.query.merchantCode;
    if(merchantCode){
      this.formList.map(item => {
        if (item.name === 'merchantCodeInput') {
          item.value= merchantCode
        }
        if (item.name === 'merchantCode') {
          item.value= merchantCode
        }
      })
    }
    //this.$refs['merchant_settle_rule_table'].onSearch()
  },
  created() {
    this.initSearchValue()
  },
  methods: {
    validateTage: util.validateTage,
    queryMerchantSettleRuleList,
    /** 平台百分比 - 商户百分比 = 100 */
    changePlatform() {
      this.$set(this.dataModule, 'merchantReceivable', (100 - this.dataModule.platformPercent) + '');
      if (this.dataModule.platformPercent.indexOf('.') > -1) {
        this.$set(this.dataModule, 'merchantReceivable', (100 - this.dataModule.platformPercent).toFixed(2));
      }
    },
    changeMerchant() {
      this.$set(this.dataModule, 'platformPercent', (100 - this.dataModule.merchantReceivable) + '');
      if (this.dataModule.merchantReceivable.indexOf('.') > -1) {
        this.$set(this.dataModule, 'platformPercent', (100 - this.dataModule.merchantReceivable).toFixed(2));
      }
    },

    // 跳转到商户页面
    gotoMerchantList (row) {
      this.$router.push({path: 'commercial', query: {
          merchantCode: row.merchantCode
        }})
    },
    add() {
      this.dataModule = {}
      this.isAddShow = true
      this.resetFormAll();
    },

    handleSubmitCancel(formName) {
      this.isAddShow = false;
    },
    handleSubmit(formName) {
      const self = this
      this.$refs[formName].validate(valid => {
        if (valid) {
          self.$Modal.confirm({
            title: "当前选择商户：",
            content: `<div class="selfConfirmRule" style="color: red;font-size: 25px;">${self.dataModule.merchantName}</div> <div class="selfConfirmRule">确认提交吗？</div>`,
            cancelText:'再想想',
            okText:'我要提交',
            closable:true,
            onOk: async () => {
              submitMerchantSettleRule(this.dataModule).then(res => {
                if (res.data.ret === 0) {
                  self.$Message.success('添加成功');
                  self.isAddShow = false;
                  self.$refs['merchant_settle_rule_table'].onSearch()
                }
              })
            }
          });
          // Modal.confirm({
          //   render: (h, params) => {
          //     return h("div", [
          //       h(
          //         "div",
          //         {
          //           class: "selfConfirmRule"
          //         },
          //         `当前选择商户为：`
          //       ),
          //       h(
          //         "div",
          //         {
          //           class: "selfConfirmRule",
          //           style:{
          //             color:'red',
          //             fontSize:'25px'
          //           }
          //         },
          //         `${self.dataModule.merchantName}`
          //       ),
          //       h(
          //         "div",
          //         {
          //           class: "selfConfirmRule"
          //         },
          //         `确认提交吗？`
          //       ),
          //     ]);
          //   },
          //   onOk: async () => {
          //     submitMerchantSettleRule(this.dataModule).then(res => {
          //       console.log('add success:', res)
          //       if (res.data.ret === 0) {
          //         self.$Message.success('添加成功');
          //         self.isAddShow = false;
          //         self.$refs['merchant_settle_rule_table'].onSearch()
          //       }
          //     })
          //
          //   }
          // });
        }
      })
    },
    /** 表单重置 */
    resetFormAll() {
      this.$refs['merchantSettleRuleModule'].resetFields()
    },

    beforeSearchSubmit(data) {
      if(data.merchantCodeInput){
        data.merchantCode=data.merchantCodeInput
      }
      return omit(data, 'date');
    },
    bindleMCode(val) {
      if (val) {
        this.dataModule.merchantName = val.label || "";
        this.dataModule.merchantCode = val.value || "";
      } else {
        this.dataModule.merchantName = "";
        this.dataModule.merchantCode = "";
      }
    },
    async initSearchValue() {
      // 查询商户
      const merchantList = await getMerchantAllMerchant();
      const selectMerchantList = merchantList.map(({merchantCode, merchantName}) => {
        return {
          value: merchantCode,
          label: merchantName
        };
      });
      this.setSearchOptionListInitValue("merchantCode", selectMerchantList)
      this.merchantList = selectMerchantList
    },
    setSearchOptionListInitValue(name, value) {
      this.formList.map(item => {
        if (item.name === name && item.props) {
          item.props.optionList = value
        }
        if(name==='merchantCode'){
          let merchantCode = this.$route.query.merchantCode;
          if (item.name === 'merchantCode' && merchantCode) {
            item.value= merchantCode
          }
        }
      })
    }
  },
};
</script>
